using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WorkFlowCore.BusinessDemo.Web.Data;
using WorkFlowCore.BusinessDemo.Web.Entities;
using WorkFlowCore.BusinessDemo.Web.Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WorkFlowCore.BusinessDemo.Web.Controllers
{
    [Route("api/user-select/roles")]
    public class UserSelectForRoleController : BaseController
    {
        private readonly BusinessDemoDbContext _context;

        public UserSelectForRoleController(BusinessDemoDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取角色选项列表
        /// </summary>
        /// <returns>角色选项列表 [{"Id":"","Name":""}]</returns>
        [HttpGet("")]
        public async Task<IActionResult> GetSelections()
        {
            var roles = await _context.Roles
                .Select(r => new Models.Selection
                {
                    Id = r.Code,
                    Name = r.Name
                })
                .ToListAsync();
            
            return Ok(roles);
        }

        /// <summary>
        /// 根据角色编号获取用户列表
        /// </summary>
        /// <param name="input">选择器输入参数</param>
        /// <returns>用户列表 [{"Id":"","Name":""}]</returns>
        [HttpPost("users")]
        public async Task<IActionResult> GetUsers([FromBody] SelectorInput input)
        {
            var roleCode = input.SelectionId;
            if (string.IsNullOrEmpty(roleCode))
            {
                return BadRequest("Invalid role code");
            }

            var users = await _context.UserRoles
                .Join(_context.Roles,
                    ur => ur.RoleId,
                    r => r.Id,
                    (ur, r) => new { UserRole = ur, Role = r })
                .Where(x => x.Role.Code == roleCode)
                .Join(_context.Users,
                    x => x.UserRole.UserId,
                    u => u.Id,
                    (x, u) => new Models.UserSelection
                    {
                    Id = u.EmployeeNumber,
                    Name = u.Name
                    })
                .ToListAsync();
            
            return Ok(users);
        }
    }
}
